package com.cqs.leetcode.hash

/**
 *
 *
 * xw
 * 2023/6/4
 */
object LongestSubstring3 {
  def main(args: Array[String]): Unit = {
    println(lengthOfLongestSubstring(""))
    println(lengthOfLongestSubstring("abcabcbb"))
    println(lengthOfLongestSubstring("bbbbb"))
    println(lengthOfLongestSubstring("pwwkew"))
  }

  def lengthOfLongestSubstring(s: String): Int = {
    var left, max = 0
    val cmap: scala.collection.mutable.Map[Char, Int] = scala.collection.mutable.Map()
    for (i <- 0 until s.length()) {
      val c: Char = s.charAt(i)
      //若存在窗口内不存在和右边界相同字符，不更新做边界
      //若存在窗口内存在和右边界相同字符且字符的索引大于左边界 更新左边届
      left = Math.max(left, 1 + cmap.getOrElse(c, -1))
      max = Math.max(max, i - left + 1)
      cmap.put(c, i)
    }
    max
  }
}
